package cn.lili.modules.auth.serviceimpl;

import cn.lili.cache.Cache;
import cn.lili.cache.CachePrefix;
import cn.lili.common.enums.ResultCode;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.security.token.Token;
import cn.lili.common.utils.BeanUtil;
import cn.lili.common.utils.StringUtils;
import cn.lili.common.utils.UuidUtils;
import cn.lili.modules.auth.mapper.ApplicationMapper;
import cn.lili.modules.auth.service.ApplicationService;
import cn.lili.modules.member.client.UserClient;
import cn.lili.modules.member.entity.dos.Application;
import cn.lili.modules.member.entity.dos.User;
import cn.lili.modules.member.entity.vo.ApplicationVO;
import cn.lili.modules.token.TokenGenerate;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * ApplicationServiceImpl
 *
 * @author Chopper
 * @version v1.0
 * 2022-08-29 14:35
 */
@Service
@RequiredArgsConstructor
public class ApplicationServiceImpl extends ServiceImpl<ApplicationMapper, Application> implements ApplicationService {


    private final UserClient userClient;

    private final TokenGenerate tokenGenerate;

    private final Cache<String> cache;

    @Override
    public ApplicationVO getByAppid(String appid) {
        LambdaQueryWrapper<Application> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Application::getAppId, appid);
        Application application = this.getOne(lambdaQueryWrapper, false);
        ApplicationVO result = new ApplicationVO();
        BeanUtil.copyProperties(application, result);
        return result;
    }

    @Override
    public String generalCode(String appid) {
        String uuid = UuidUtils.getUUID();
        //默认120秒有效
        cache.put(CachePrefix.OAUTH2_CODE.getPrefix() + uuid, UserContext.getCurrentId(), 120L);
        return uuid;
    }

    @Override
    public Token login(String appid, String code) {
        String userid = cache.get(CachePrefix.OAUTH2_CODE.getPrefix() + code);
        if (StringUtils.isEmpty(userid)) {
            throw new ServiceException(ResultCode.OAUTH_CODE_EMPTY);
        }

        User user = userClient.getById(userid);
        return tokenGenerate.generateToken(user, false);
    }
}
